import type { UploadedImage } from '../types/models';
import { v4 as uuidv4 } from 'uuid';
import { createImageFromFile, getImageFormat } from '../utils/imageUtils';
import { validateImageDimensions, validateImageCount } from '../utils/validationUtils';
import { processBatch, releaseMemory } from '../utils/memoryUtils';
import { ValidationError } from '../utils/errorUtils';

/**
 * Service for handling image upload operations
 */
export class ImageUploadService {
  /**
   * Upload multiple images
   * @param files Files to upload
   * @returns Promise with array of uploaded images
   */
  /**
   * Upload multiple images with progress tracking
   * @param files Files to upload
   * @param onProgress Optional callback for progress updates
   * @returns Promise with array of uploaded images
   */
  async uploadImages(
    files: File[], 
    onProgress?: (progress: number) => void
  ): Promise<UploadedImage[]> {
    const validFiles = files.filter(file => this.validateImage(file));
    
    if (validFiles.length === 0) {
      throw new ValidationError('没有有效的图片文件');
    }
    
    // Process files in batches using our utility function
    const uploadedImages = await processBatch<File, UploadedImage>(
      validFiles,
      3, // Process 3 images at a time
      async (file) => {
        try {
          // Load image to get dimensions
          const img = await createImageFromFile(file);
          
          // Validate image dimensions
          const dimensionsValidation = validateImageDimensions(img.width, img.height);
          if (!dimensionsValidation.valid) {
            console.error(dimensionsValidation.message);
            return null;
          }
          
          // Create uploaded image object
          const uploadedImage: UploadedImage = {
            id: uuidv4(),
            file,
            url: URL.createObjectURL(file),
            name: file.name,
            width: img.width,
            height: img.height,
            fileSize: file.size,
            format: getImageFormat(file)
          };
          
          return uploadedImage;
        } catch (error) {
          console.error('处理图片失败:', error);
          return null;
        }
      },
      onProgress
    );
    
    // Release memory after processing
    releaseMemory();
    
    return uploadedImages;
  }

  /**
   * Remove an image by id
   * @param id Image id to remove
   */
  removeImage(_id: string): void {
    // This is handled by the store
  }

  /**
   * Get all uploaded images
   * @returns Array of uploaded images
   */
  getUploadedImages(): UploadedImage[] {
    // This is handled by the store
    return [];
  }

  /**
   * Validate if an image file is valid
   * @param file File to validate
   * @returns True if valid, false otherwise
   */
  validateImage(file: File): boolean {
    // Check if file is an image
    if (!file.type.startsWith('image/')) {
      console.error('Invalid file type:', file.type);
      return false;
    }
    
    // Check supported formats
    const supportedFormats = ['image/jpeg', 'image/png', 'image/webp'];
    if (!supportedFormats.includes(file.type)) {
      console.error('Unsupported image format:', file.type);
      return false;
    }
    
    // Check file size (max 50MB)
    const maxSize = 50 * 1024 * 1024; // 50MB
    if (file.size > maxSize) {
      console.error('File too large:', file.size);
      return false;
    }
    
    return true;
  }
  
  /**
   * Validate if adding more images would exceed limits
   * @param currentCount Current number of images
   * @param addingCount Number of images being added
   * @returns Object with validation result and error message
   */
  validateImageCount(currentCount: number, addingCount: number): { valid: boolean; message?: string } {
    return validateImageCount(currentCount, addingCount);
  }
}

export default new ImageUploadService();